package com.vs.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.vs.common.InvalidUserException;
import com.vs.model.LoginForm;
import com.vs.model.User;

public class Security {

	private String queryString = "select user_id,user_name,user_type from users where user_name=? and user_pass=? ";
	
	public User validateUser(LoginForm loginForm) throws InvalidUserException{
		Connection conn = null;
		User user = null;
		System.out.println("validateUser called");
		try {
			conn = new DBConnection().getConnection();
			if (conn == null) {
				System.out.println("conn not found");
			} else {
				// System.out.println("conn found");
			}
			
			PreparedStatement ps = conn.prepareStatement(queryString);
			ps.setString(1, loginForm.getUsername());
			ps.setString(2, loginForm.getPassword());
			ResultSet rs = ps.executeQuery();
			
			if(rs.next())
			{
				user = new User();
				user.setUserId(rs.getInt("user_id"));
				user.setUserName(rs.getString("user_name"));
				user.setUserType(rs.getString("user_type"));
			}
			else
			{
				throw new InvalidUserException("User " + loginForm.getUsername() + " not found in the system");
			}
			
			rs.close();
			ps.close();
			
		} catch (Exception e) {
			
		}
		
		return user;
	}
}
